import { createFetch } from '@vueuse/core'
import { message } from 'ant-design-vue'
import router from '../router/index';

export const baseUrl = 'http://127.0.0.1:8000'

export const useCustomFetch = createFetch({
  baseUrl,
  options: {
    afterFetch(ctx) {
      const globalConfigStore = useGlobalConfigStore()
      const permissionStore = usePermissionStore()
      if (ctx.data) {
        ctx.data = JSON.parse(ctx.data)
        if (ctx.data.code === 401) {
          message.error(ctx.data.msg ?? ctx.data.message)
          // 清除 Pinia 中的数据
          globalConfigStore.setLoginToken('')
          globalConfigStore.config.projectId = null as any
          globalConfigStore.config.projectDatas = null as any
          globalConfigStore.config.projectListDataProxy = null as any
          // 清除 localStorage 中的数据
          localStorage.clear()
          // 清除权限数据
          permissionStore.roles = '' as any
          router.push('/')
        } else if (ctx.data.code !== 0) {
          message.error(ctx.data.msg ?? ctx.data.message)
        }
      }
      return ctx
    },
    beforeFetch({ options, url }) {
      const globalConfigStore = useGlobalConfigStore()
      if (!options.method) return

      if (globalConfigStore.isLogin) {
        options.headers = {
          ...options.headers,
          satoken: `${globalConfigStore.loginToken}`,
        }

        if (
          ['POST', 'PUT'].includes(options.method.toUpperCase()) &&
          options.body
        ) {
          options.body = JSON.stringify({
            ...JSON.parse(options.body as string),
            projectId: globalConfigStore.config.projectId,
          })
        } else if (options.method === 'GET') {
          url = handleParams(url, {
            projectId: globalConfigStore.config.projectId,
          })
        }
      }

      return {
        url,
        options,
      }
    },
  },
  fetchOptions: {
    headers: {
      'Content-Type': 'application/json',
    },
  },
})
